package com.rslai.commons.util;

import java.lang.reflect.Field;

/**
 * 枚举工具类
 */
public class EnumUtil {

    /**
     * 将传入的 value值 转成枚举（int 类型 value 转枚举）
     * @param enumClass 枚举类型
     * @param value 传入的 value值
     * @return
     * @param <T>
     */
    public static <T extends Enum<T>> T valueOf(Class<T> enumClass, int value) {
        T[] enumConstants = enumClass.getEnumConstants();
        for (T enumConstant : enumConstants) {
            Field field;
            try {
                field = enumClass.getDeclaredField("value");
            } catch (NoSuchFieldException e) {
                continue;
            }
            field.setAccessible(true);
            int fieldValue;
            try {
                fieldValue = field.getInt(enumConstant);
            } catch (IllegalAccessException e) {
                continue;
            }
            if (fieldValue == value) {
                return enumConstant;
            }
        }
        throw new IllegalArgumentException("No enum constant with value " + value);
    }

    /**
     * 将传入的 value值 转成枚举（String 类型 value 转枚举）
     * @param enumClass 枚举类型
     * @param value 传入的 value值
     * @return
     * @param <T>
     */
    public static <T extends Enum<T>> T valueOf(Class<T> enumClass, String value) {
        T[] enumConstants = enumClass.getEnumConstants();
        for (T enumConstant : enumConstants) {
            Field field;
            try {
                field = enumClass.getDeclaredField("value");
            } catch (NoSuchFieldException e) {
                continue;
            }
            field.setAccessible(true);
            String fieldValue;
            try {
                fieldValue = field.get(enumConstant).toString();
            } catch (IllegalAccessException e) {
                continue;
            }
            if (value.equalsIgnoreCase(fieldValue)) {
                return enumConstant;
            }
        }
        throw new IllegalArgumentException("No enum constant with value " + value);
    }
}
